package cn.schoolwow.quickdao.test.module.business.ddl.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.dql.condition.Condition;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickdao.test.module.business.ddl.domain.JoinTableDefine;
import cn.schoolwow.quickdao.test.module.business.ddl.domain.QueryTableColumnDefine;
import cn.schoolwow.quickdao.test.module.business.ddl.domain.QueryTableDefine;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.resource.QueryResource;
import com.alibaba.fastjson.JSONArray;

public class QueryTableDefineFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);
        DatabaseProvider databaseProvider = dao.getDatabaseProvider();

        QueryTableDefine queryTableDefine = QueryResource.newQuery("自定义表查询", "module/business/ddl/表查询/查询用户列表.json")
                .execute()
                .getAsInstance(QueryTableDefine.class);
        for(QueryTableColumnDefine queryTableColumnDefine:queryTableDefine.queryTableColumnDefineList){
            queryTableColumnDefine.tableName = databaseProvider.escape(queryTableColumnDefine.tableName);
            queryTableColumnDefine.column = databaseProvider.escape(queryTableColumnDefine.column);
            if(null!=queryTableColumnDefine.tableName&&!queryTableColumnDefine.tableName.isEmpty()){
                queryTableColumnDefine.tableName = queryTableColumnDefine.tableName+".";
            }
        }

        Condition condition = dao.query(queryTableDefine.tableName)
                .tableAliasName(queryTableDefine.tableName);
        for(JoinTableDefine joinTableDefine:queryTableDefine.joinTableDefineList){
            if(null==joinTableDefine.tableAliasName){
                joinTableDefine.tableAliasName = joinTableDefine.tableName;
            }
            condition.joinTable(joinTableDefine.tableName, joinTableDefine.primaryTableColumn, joinTableDefine.joinTableColumn)
                    .tableAliasName(joinTableDefine.tableAliasName);
        }
        for(QueryTableColumnDefine queryTableColumnDefine:queryTableDefine.queryTableColumnDefineList){
            if(null!=queryTableColumnDefine.columnAliasName){
                condition.addColumnAs(queryTableColumnDefine.tableName+queryTableColumnDefine.column, queryTableColumnDefine.columnAliasName);
            }else{
                condition.addColumn(queryTableColumnDefine.tableName+queryTableColumnDefine.column);
            }
        }
        JSONArray array = condition.execute().getArray();
        System.out.println(array.toJSONString());
    }

    @Override
    public String name() {
        return "自定义表关联查询";
    }
}
